package com.muyu.gateway.filter;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.muyu.common.core.utils.ServletUtils;
import com.muyu.common.core.utils.StringUtils;
import com.muyu.gateway.config.properties.CaptchaProperties;
import com.muyu.gateway.service.ValidateCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 验证码过滤器
 *
 * @author muyu
 */
@Component
public class ValidateCodeFilter extends AbstractGatewayFilterFactory<Object> {
    private final static String[] VALIDATE_URL = new String[]{"/auth/login", "/auth/register"};
    private static final String CODE = "code";
    private static final String UUID = "uuid";

    private final ValidateCodeService validateCodeService;

    private final CaptchaProperties captchaProperties;

    @Autowired
    public ValidateCodeFilter(ValidateCodeService validateCodeService, CaptchaProperties captchaProperties) {
        this.validateCodeService = validateCodeService;
        this.captchaProperties = captchaProperties;
    }

    public ValidateCodeFilter(Class<Object> configClass, ValidateCodeService validateCodeService, CaptchaProperties captchaProperties) {
        super(configClass);
        this.validateCodeService = validateCodeService;
        this.captchaProperties = captchaProperties;
    }

    @Override
    public GatewayFilter apply (Object config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();

            // 非登录/注册请求或验证码关闭，不处理
            if (!StringUtils.equalsAnyIgnoreCase(request.getURI().getPath(), VALIDATE_URL) || !captchaProperties.getEnabled()) {
                return chain.filter(exchange);
            }

            try {
                String rspStr = resolveBodyFromRequest(request);
                JSONObject obj = JSON.parseObject(rspStr);
                validateCodeService.checkCaptcha(obj.getString(CODE), obj.getString(UUID));
            } catch (Exception e) {
                return ServletUtils.webFluxResponseWriter(exchange.getResponse(), e.getMessage());
            }
            return chain.filter(exchange);
        };
    }

    private String resolveBodyFromRequest (ServerHttpRequest serverHttpRequest) {
        // 获取请求体
        Flux<DataBuffer> dataBufferFlux = serverHttpRequest.getBody();
        AtomicReference<String> bodyStr = new AtomicReference<>();
        dataBufferFlux.cache().subscribe(dataBuffer -> {
            byte[] bytes = new byte[dataBuffer.readableByteCount()];
            dataBuffer.read(bytes);
            bodyStr.set(new String(bytes, StandardCharsets.UTF_8));
        });
        return bodyStr.get();
    }
}
